import streamlit as st
import streamlit_authenticator as stauth
import yaml

from streamlit_authenticator.utilities.exceptions import (CredentialsError,
                                                          ForgotError,
                                                          LoginError,
                                                          RegisterError,
                                                          ResetError,
                                                          UpdateError) 
from mypages.secure_page import secure_page_fun

from mypages.pokemon import pk_table,plot_demo1,plot_demo2

from mypages.university import my_table,citation_vs_rank_scatter

with open('st_auth/config.yaml') as file:
    config = yaml.load(file, Loader=yaml.SafeLoader)
    
authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['pre-authorized']
)


def main():
    # 创建侧边栏登录
    try:
        authenticator.login()
    except LoginError as e:
        st.error(e)

    # 页面选择
    PAGES = {
        "主页": home,
        "安全页面": secure_page_fun,
        "Reset Password": reset_pwd,
        "Registration": registration,
        "Update User Details": update_user_details,
        "宝可梦": pk_table,
        "宝可梦2": plot_demo1,
        "水属性和火属性宝可梦的对比": plot_demo2,
        "注销":logout,
        '学校排名': my_table,
        '学校的论文引用与排名的关系':citation_vs_rank_scatter
    }

    # 根据登录状态显示页面
    if st.session_state["authentication_status"]:
        st.sidebar.success(f'Logged in as {st.session_state["name"]}')
        page = st.sidebar.radio('Go to', list(PAGES.keys()))
        PAGES[page]()
    elif st.session_state["authentication_status"] == False:
        st.sidebar.error('Username/password is incorrect')
    elif st.session_state["authentication_status"] == None:
        st.sidebar.warning('Please enter your username and password')

def logout():
    authenticator.logout()
    
# 定义页面函数
def home():
    if st.session_state["authentication_status"]:
        st.title('Home Page')
        st.write('Welcome to the home page!')
    else:
        st.error("You are not logged in. Please log in to access the home page.")


def registration():
    try:
        (email_of_registered_user,
            username_of_registered_user,
            name_of_registered_user) = authenticator.register_user(pre_authorization=False)
        if email_of_registered_user:
            st.success('User registered successfully')
            # 保持用户信息到配置文件
            save()
    except RegisterError as e:
        st.error(e)
        
def save():
     with open('st_auth/config.yaml', 'w', encoding='utf-8') as file:
         yaml.dump(config, file, default_flow_style=False)
         
def reset_pwd():
    if st.session_state["authentication_status"]:
        try:
            if authenticator.reset_password(st.session_state["username"]):
                st.success('Password modified successfully')
                  # 保持用户信息到配置文件
                save()
        except ResetError as e:
            st.error(e)
        except CredentialsError as e:
            st.error(e)
            
def update_user_details():
    if st.session_state["authentication_status"]:
        try:
            if authenticator.update_user_details(st.session_state["username"]):
                st.success('Entries updated successfully')
                  # 保持用户信息到配置文件
                save()
        except UpdateError as e:
            st.error(e)

if __name__ == '__main__':
    main()